import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gameplay_flutter/lib_runtime/extension/string_extension/string_text.dart';

class RoomPwd extends StatefulWidget {
  const RoomPwd({Key? key}) : super(key: key);

  @override
  _RoomPwdState createState() => _RoomPwdState();
}

class _RoomPwdState extends State<RoomPwd> {
  final List<TextEditingController> _controllers = List.generate(
    4,
    (index) => TextEditingController(),
  );

  final List<FocusNode> _focusNodes = List.generate(
    4,
    (index) => FocusNode(),
  );

  @override
  void initState() {
    super.initState();
    _setupFocusListeners();
  }

  @override
  void dispose() {
    for (var controller in _controllers) {
      controller.dispose();
    }
    for (var node in _focusNodes) {
      node.dispose();
    }
    super.dispose();
  }

  void _setupFocusListeners() {
    for (int i = 0; i < 4; i++) {
      _focusNodes[i].addListener(() {
        if (!_focusNodes[i].hasFocus && _controllers[i].text.isEmpty) {
          _controllers[i].text = '';
        }
      });
    }
  }

  void _handleInput(String value, int index) {
    if (value.isNotEmpty) {
      if (index < 3) {
        _focusNodes[index].unfocus();
        FocusScope.of(context).requestFocus(_focusNodes[index + 1]);
      }
    }
  }

  void _handleBackspace(int index) {
    if (_controllers[index].text.isEmpty && index > 0) {
      _controllers[index - 1].text = '';
      FocusScope.of(context).requestFocus(_focusNodes[index - 1]);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 196.h,
      padding: EdgeInsets.only(bottom: 10.h,left: 20.w,right: 20.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18.r),
      ),
      child: Column(
        children: [
          SizedBox(
            height: 12.h,
          ),
          "Room Code".text(
            fontSize: 20.sp,
            color: Colors.black,
            weight: TextFontWeight.medium,
          ),
          _inputPwd(),
          Container(
            height: 37.h,
            width: 204.w,
            margin: EdgeInsetsDirectional.symmetric(vertical: 7.h),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                colors: [
                  Color(0xFF8A72FE),
                  Color(0xFF6549EC),
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
              borderRadius: BorderRadius.circular(24.r),
            ),
            child: "Save".text(
              fontSize: 20.sp,
              color: Colors.white,
              weight: TextFontWeight.medium,
            ),
          ),
          "Cancel".text(
            fontSize: 14.sp,
            color: const Color(0xFFA8A8A8),
          ),
        ],
      ),
    );
  }

  Widget _inputPwd() {
    return Expanded(
      child: KeyboardListener(
        // 替换为 KeyboardListener
        focusNode: FocusNode(),
        onKeyEvent: (event) {
          // 仅处理按下事件且是删除键
          if (event is KeyDownEvent &&
              event.logicalKey == LogicalKeyboardKey.backspace) {
            for (int i = 3; i >= 0; i--) {
              if (_focusNodes[i].hasFocus || _controllers[i].text.isNotEmpty) {
                _handleBackspace(i);
                break;
              }
            }
          }
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: List.generate(4, (index) {
            return Container(
              width: 50,
              height: 58,
              alignment: Alignment.center,
              padding: EdgeInsetsDirectional.only(bottom: 6.h),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8.r),
                color: const Color(0xFFF3F3F3),
              ),
              child: TextField(
                controller: _controllers[index],
                focusNode: _focusNodes[index],
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 32.sp,
                  color: const Color(0xFF1B1B1B),
                  fontWeight: FontWeight.w500,
                ),
                cursorHeight: 25.h,
                keyboardType: TextInputType.number,
                maxLength: 1,
                decoration: const InputDecoration(
                  counterText: '',
                  border:  InputBorder.none,
                ),
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                  LengthLimitingTextInputFormatter(1),
                ],
                onChanged: (value) => _handleInput(value, index),
              ),
            );
          }),
        ),
      ),
    );
  }
}
